package org.zxy.org.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;
import org.zxy.base.util.ImportExcelUtil;
import org.zxy.org.domain.Department;
import org.zxy.org.service.IEmployeeService;
import org.zxy.org.domain.Employee;
import org.zxy.org.query.EmployeeQuery;
import org.zxy.base.util.AjaxResult;
import org.zxy.base.util.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/employee" )
public class EmployeeController {
    @Autowired
    public IEmployeeService employeeService;


    /**
     * 保存和修改
     * @param employee 传递的实体
     * @return Ajaxresult转换结果
     */
    @PutMapping
    public AjaxResult insertOrUpdate(@RequestBody Employee employee) {
        try {
            if ( employee.getId() != null)
                employeeService.update(employee);
            else
                employeeService.insert(employee);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("保存对象失败！" + e.getMessage());
        }
    }

    /**
    * 删除对象信息
    * @param id
    * @return
    */
    @DeleteMapping(value = "/{id}" )
    public AjaxResult deleteById(@PathVariable("id" ) Long id) {
        try {
                employeeService.deleteById(id);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("删除对象失败！" + e.getMessage());
        }
    }
    /**
     * 根据Id查询对象信息
     * @param
     * @return
     */
    //获取用户
    @GetMapping("/{id}" )
    public AjaxResult selectById(@PathVariable("id" ) Long id) {
        try {
            Employee employee =employeeService.selectById(id);
            return AjaxResult.success(employee);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取一个失败！" + e.getMessage());
        }
    }


    /**
    * 查看所有对象信息
    * @return
    */
    @GetMapping
    public AjaxResult selectAll() {

        try {
            List< Employee> list = employeeService.selectAll();
            return AjaxResult.success(list);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取所有失败！" + e.getMessage());
        }
    }


    /**
    * 分页查询数据
    *
    * @param query 查询对象
    * @return PageList 分页对象
    */
    @PostMapping
    public AjaxResult queryPage(@RequestBody EmployeeQuery query) {
        try {
            PageList<Employee> pageList = employeeService.queryPage(query);
            return AjaxResult.success(pageList);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取分页数据失败！" + e.getMessage());
        }
    }

    /**
     * 批量删除对象
     *
     * @param
     * @return
     */
    @PatchMapping
    public AjaxResult batchDelete(@RequestBody List<Long> ids) {
        try {
                employeeService.batchDelete(ids);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("批量删除失败！" + e.getMessage());
        }
    }
    /*
   导入文件的接口
    */
    @PostMapping("/excel")
    public AjaxResult importExcel(MultipartFile file) {
        try {
            //生成一个导入模板
            ImportParams params = new ImportParams();
            //设置表格标题行数,默认0，这是读取时会跳过的行数
            params.setHeadRows(1);
            //开始读取，并用list接收，方便处理
            List<Employee> employeeList = ExcelImportUtil.importExcel(file.getInputStream(), Employee.class, params);
            System.out.println(employeeList);
            System.out.println(employeeList.size());
            //错误的列表
            System.out.println("=====================================");
            List<Employee> errorList = ImportExcelUtil.verifyEmail(employeeList);
            System.out.println(errorList);
            System.out.println("===================================");
            if (errorList == null) {
                //将excel表格的数据添加到数据库
                employeeService.importExcel(employeeList);
                return AjaxResult.success();
            }else{
                employeeList.removeAll(errorList);
                employeeService.importExcel(employeeList);
                //打印错误的员工数据
                ObjectMapper objectMapper = new ObjectMapper();
                //将错误的数据复制到一个新的集合中
                List<Employee> errorListCopy = new ArrayList<>();
                /*
                objectMapper.readValue 是 Jackson 库中的方法，
                用于反序列化 JSON 对象或将 JSON 字符串转换为 Java 对象。
                该方法的作用是将 JSON 数据转换为使用 Java对象表示的数据。
                objectMapper.writeValueAsString 方法用于将 Java 对象序列化为 JSON 字符串
                 */
                for (Employee employee:errorList) {
                    Employee employee1 = objectMapper.readValue(objectMapper.writeValueAsString(employee), Employee.class);
                    Department department1 = objectMapper.readValue(objectMapper.writeValueAsString(employee.getDepartment()), Department.class);
                    employee1.setDepartment(department1);
                    errorListCopy.add(employee1);
                }
                //生成一个导出模板
                ExportParams exportParams = new ExportParams();
                Workbook workbook = ExcelExportUtil.exportExcel(exportParams, Employee.class, errorList);
                //导出的地址
                FileOutputStream os = new FileOutputStream("C:\\Users\\赵鑫宇\\Desktop\\errorEmployeeData.xls");
                workbook.write(os);
                os.close();
                workbook.close();
                return AjaxResult.error(errorListCopy);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }
    //将错误数据导出到界面
    @PostMapping("/error")
    public AjaxResult errorData(MultipartFile file){
        try {
            //生成一个导入模板
            ImportParams params = new ImportParams();
            //设置表格标题行数,默认0，这是读取时会跳过的行数
            params.setHeadRows(1);
            //开始读取，并用list接收，方便处理
            List<Employee> employeeList = ExcelImportUtil.importExcel(file.getInputStream(), Employee.class, params);
            //错误的列表
            System.out.println("=====================================");
            List<Employee> errorList = ImportExcelUtil.verifyEmail(employeeList);
            System.out.println("===================================");
            return AjaxResult.success(errorList);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("导入失败！" + e.getMessage());
        }
    }



    /*
    导出文件的接口
     */
    @PostMapping("/exportExcel")
    public AjaxResult exportExcel(HttpServletRequest request){
        try {
            String key = request.getHeader("key");
            System.out.println(key);
            employeeService.exportExcel(key);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }

    }

}
